var createError = require('http-errors')
var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')
var cors = require('cors')
// 引入multer 模块解决文件上传问题
const multer = require('multer')

var indexRouter = require('./routes/index')
var loginRouter = require('./routes/loginUser')
var userRouter = require('./routes/user')
const articleRouter = require('./routes/article')
const endIndexRouter = require('./routes/endIndex')
const talkRouter = require('./routes/talk')
const messageRouter = require('./routes/message')
const commentRouter = require('./routes/comment')
const emailerRouter = require('./routes/emailer.js')
const JWT = require('./util/jwt.js')
const compression = require('compression')
//配置一个文件夹放传来的图片资源
const upload = multer({ dest: 'public/avatarUploads/' })
// const  frontUploads= multer({ dest: "public/frontUploads/" });
const uploadPcAvatar = multer({ dest: 'public/pcAvatar/' })
const storage = multer.diskStorage({
  destination: function (req, file, cd) {
    cd(null, 'public/frontUploads/')
  },
  filename: function (req, file, cd) {
    console.log(req.originalUrl)
    if (req.originalUrl == '/message/messageImg') {
      cd(null, 'messageImage.jpg')
    } else if (req.originalUrl == '/endIndex/footerCode') {
      cd(null, 'footerCode.jpg')
    } else {
      cd(null, 'frontImage.jpg')
    }
  },
})
const frontUploads = multer({ storage })
const messagePage = multer({ storage })
const uploadArticle = multer({ dest: 'public/articleUploads/' })
var app = express()
//  可以压缩文件 虽然我是前后端分离
app.use(compression())
// 解决跨域问题
// app.use(cors({
//   // 配置主机端口
//   origin:'http://localhost:8080'
// }))
app.use(cors())
// 配置全局拦截
// 定义拦截验证token
app.use((req, res, next) => {
  if (req.url.includes('login')) {
    next()
    return
  }
  let token = req.headers.token?.split(' ')[1]
  if (token) {
    let payload = JWT.verify(token)
    if (payload) {
      let token = JWT.generate(
        {
          uname: payload.uname,
        },
        '10h'
      )
      res.setHeader('Access-Control-Expose-Headers', 'Authorization')
      res.header('Authorization', token)
      next()
    } else {
      res.status(401).send({ errInof: 'token过期', ok: 0 })
    }
  } else {
    next()
  }
})
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

app.use('/', indexRouter)
app.use('/comment', commentRouter)
app.use('/login/user', loginRouter)
app.use('/talk', talkRouter)
app.use('/message', messagePage.single('file'), messageRouter)
app.use('/endIndex', frontUploads.single('file'), endIndexRouter)
app.use('/user', upload.single('avatar'), userRouter)
app.use('/article', uploadArticle.single('file'), articleRouter)
// 验证邮箱
app.use('/emailer', uploadPcAvatar.single('avatar'), emailerRouter)
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404))
})

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}

  // render the error page
  res.status(err.status || 500)
  res.render('error')
})

module.exports = app
